package org.shreker.shan.core.service.impl;

import java.util.concurrent.ThreadLocalRandom;
import org.shreker.shan.core.domain.User;
import org.shreker.shan.core.mapper.UserMapper;
import org.shreker.shan.core.service.IUserService;
import org.shreker.shan.core.util.BitUtil;
import org.shreker.shan.core.util.LoginContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements IUserService {

	@Autowired
	private UserMapper userMapper;

	@Override
	public void save(User user) throws Exception {
		userMapper.insert(user);
	}

	@Override
	public User get(Long id) throws Exception {
		return userMapper.selectByPrimaryKey(id);
	}

	@Override
	public void sendVerifyCode(String phone) throws Exception {
		// 连接远程的短信网关服务器, 我们调用别人服务器的接口, 进行短信的发送
		// 短信网关的服务器短信发送成功之后会给我们一个回执
		String source = "1234567890abcdefghijklmnopqrstuvwxyz";
		StringBuilder builder = new StringBuilder();
		for (int i = 0; i < 6; i++) {
			ThreadLocalRandom random = ThreadLocalRandom.current();
			int index = random.nextInt(0, source.length());
			builder.append(source.substring(index, index + 1));
		}
		System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
		System.out.println(builder);
		System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
		updateCode(LoginContext.getCurrentLogin().getId(), builder.toString());
		// 需要我们做一个定时器, 到时间后, 主动清空用户表中的验证码字段
	}

	@Override
	public void updateCode(Long id, String code) throws Exception {
		User user = new User();
		user.setId(id);
		user.setTempVerifiedCode(code);
		userMapper.updateCodeByPrimaryKey(user);
	}

	@Override
	public void verifyPhone(String phone, String code) {
		// 1. 验证验证码的正确性
		User user = userMapper.selectByPrimaryKey(LoginContext.getCurrentLogin().getId());
		String codeInDB = user.getTempVerifiedCode();
		if (codeInDB == null) {
			throw new RuntimeException("验证码错误或已过期");
		}

		// 2. 验证要绑定的手机的合法性(是否已经有人绑定该手机)
		Long phoneCount = userMapper.selectPhoneCount(phone);
		if (phoneCount >= 1) {
			throw new RuntimeException("该手机已在其他账户绑定!");
		} else {
			if (user.getTempVerifiedCode().equals(code)) {
				// 手机验证成功, 绑定手机到用户账户
				user.setPhone(phone);
				// 更新用户的手机认证状态
				user.setBitState(BitUtil.merge(user.getBitState(), User.BITSTATE_PHONE_AUTHENTICATION));
				userMapper.updateByPrimaryKey(user);
			} else {
				throw new RuntimeException("验证码不正确!");
			}
		}

	}

}
